package com.feihao.zhou.demo1;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class XMLParse {
    public static void main(String[] args) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        //创建list集合存储学生：
        ArrayList<Student> list = new ArrayList<>();

        //获取文本对象
//        Document document = saxReader.read("D:\\IdeaProjects\\Job-code\\day18-code-XML-EUNM\\xml\\Studnet.xml");
        Document document = saxReader.read(new File("D:\\IdeaProjects\\Job-code\\day18-code-XML-EUNM\\xml\\Studnet.xml"));

        //获取document对象的根标签
        Element rootElement = document.getRootElement();
//        System.out.println(rootElement);
        //通过根标签获取student标签组
        List<Element> student = rootElement.elements("student");
        //通过遍历student组标签获取每个标签里面的元素：
        for (Element element : student) {
            //获取id:
            Attribute attribute = element.attribute("id");
            String id = attribute.getValue();
            System.out.println(id);

            //获取姓名
            Element element1 = element.element("name");
            String name = element1.getText();

            //获取年龄
            Element element2 = element.element("age");
            String age = element2.getText();

            //封装学生对象：
            Student student00 = new Student(name, id, Integer.parseInt(age));
            list.add(student00);

        }

        for (Student student1 : list) {
            System.out.println(student1);
        }

        //获取message信息：
        List<Element> student1 = rootElement.elements("student");
        /*Element s2 = student1.remove(1);
        Element message = s2.element("message");
        String text = message.getText();
        System.out.println(text);*/

        //第二种：
        /*for (int i = 0; i < student1.size(); i++) {
            Element element = student1.get(i);
            if (element.attribute("id").getValue().equals("2")){
                Element message = element.element("message");
                System.out.println(message.getText());
            }
        }*/

        //第三种：
        for (int i = 0; i < student1.size(); i++) {
            Element element = student1.get(i);
            if (element.element("message")!=null){
                String message = element.element("message").getText();
                System.out.println(message);
            }
        }

    }

}
